package top.frsf.dashboard.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.frsf.dashboard.config.BrokerStats;
import top.frsf.dashboard.pojo.vo.ClientVO;
import top.frsf.dashboard.pojo.vo.DashboardVO;
import top.frsf.dashboard.pojo.vo.Result;
import top.frsf.mqtt.properties.ServerProperties;
import top.frsf.mqtt.session.SessionManager;

import java.util.Collection;

/**
 * 仪表盘接口
 *
 * @author He Kuntao
 * @since 2025/6/3 14:27
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class DashboardController {

    private final BrokerStats brokerStats;

    private final SessionManager sessionManager;

    private final ServerProperties serverProperties;

    /**
     * 获取仪表盘统计数据
     */
    @GetMapping("/dashboard")
    public Result<DashboardVO> getDashboardData() {
        DashboardVO data = DashboardVO.builder()
                .activeClients(sessionManager.getClients().size())
                .topicCount(sessionManager.getSubscriberCount())
                .totalMessages(brokerStats.getMessagesSent().get() + brokerStats.getMessagesReceived().get())
                .runTime(brokerStats.getUptime())
                .port(serverProperties.getPort())
                .protocolVersion("MQTT 3.1.1")
                .maxClientQueue(serverProperties.getBacklog())
                .keepAlive(serverProperties.isKeepAlive())
                .build();
        return Result.success(data);
    }

    @GetMapping("/clients")
    public Result<Collection<ClientVO>> getClients() {
        return Result.success(sessionManager.getClientInfos());
    }

}
